package org.xiangfei.demo.netty;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.xiangfei.demo.netty.codec.User;

/**
 * https://waylau.com/netty-chat/
 * @author fee
 *
 */
public class SimpleChatServerHandler extends SimpleChannelInboundHandler<Object> {
    // 总共多少个channel
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // usertoken 对应的channel
    private static Map<String,Channel> channelMap=new ConcurrentHashMap<String, Channel>();
   
    public static void addChannel(String clientId,Channel socketChannel){
        channelMap.put(clientId,socketChannel);
    }
    public static Channel getChannel(String clientId){
       return channelMap.get(clientId);
    }
    public static void removeChannel(Channel socketChannel){
        for (Map.Entry entry:channelMap.entrySet()){
            if (entry.getValue()==socketChannel){
                channelMap.remove(entry.getKey());
            }
        }
    }
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
       
        // Broadcast a message to multiple Channels
        channels.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 加入\n");
        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
        Channel incoming = ctx.channel();
        // Broadcast a message to multiple Channels
        channels.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // (4)
        System.out.println("操你老母");
        User user = (User)msg;
        System.out.println(user.getBody());
//        System.out.println("服务器读取user"  + user.getName() + ":" + user.getBody());
//        user.setBody("哈哈等方式史蒂夫" + user.getUserToken());
//        addChannel(user.getUserToken(), ctx.channel());
//        
//        String userToken2 = SimpleChatServer.userMap.get(user.getUserToken());
//        if (channelMap.get(userToken2) != null) {
//            channelMap.get(userToken2).writeAndFlush(user);
//        } else {
//            channelMap.get(user.getUserToken()).writeAndFlush(user);
//        }
//        // Channel incoming = ctx.channel();
        // for (Channel channel : channels) {
        // if (channel != incoming){
        // channel.writeAndFlush("[" + incoming.remoteAddress() + "]" + s +
        // "\n");
        // } else {
        // channel.writeAndFlush("[you]" + s + "\n");
        // }
        // }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端激活" + incoming.remoteAddress() + "在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端掉线" + incoming.remoteAddress() + "掉线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
        Channel incoming = ctx.channel();
        System.out.println("SimpleChatClient: 客户端异常" + incoming.remoteAddress() + "异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
